package com.dlc.shop.platform.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.dlc.shop.bean.dto.SkuAdminDTO;
import com.dlc.shop.bean.dto.TranslateRequestDto;
import com.dlc.shop.bean.dto.TranslateResponDto;
import com.dlc.shop.bean.enums.*;
import com.dlc.shop.bean.event.*;
import com.dlc.shop.bean.model.*;
import com.dlc.shop.bean.param.NotifyTemplateParam;
import com.dlc.shop.bean.param.OfflineHandleEventAuditParam;
import com.dlc.shop.bean.param.ProductParam;
import com.dlc.shop.bean.vo.ComboProdSkuVO;
import com.dlc.shop.bean.vo.ComboProdVO;
import com.dlc.shop.bean.vo.StockPointVO;
import com.dlc.shop.combo.multishop.model.ComboProd;
import com.dlc.shop.combo.multishop.service.ComboProdService;
import com.dlc.shop.combo.multishop.service.GiveawayProdService;
import com.dlc.shop.common.config.Constant;
import com.dlc.shop.common.constants.SegmentIdKey;
import com.dlc.shop.common.enums.StatusEnum;
import com.dlc.shop.common.enums.SysTypeEnum;
import com.dlc.shop.common.exception.YamiShopBindException;
import com.dlc.shop.common.i18n.I18nMessage;
import com.dlc.shop.common.response.ServerResponseEntity;
import com.dlc.shop.common.translate.TranslateUtil;
import com.dlc.shop.common.util.PageParam;
import com.dlc.shop.delivery.common.model.Transport;
import com.dlc.shop.distribution.common.dto.DistributionUserWalletBillDto;
import com.dlc.shop.distribution.common.model.DistributionUser;
import com.dlc.shop.jky.common.foreign.service.ForeignProductService;
import com.dlc.shop.jky.common.foreign.service.ForeignShopService;
import com.dlc.shop.seckill.common.service.SeckillService;
import com.dlc.shop.security.common.util.AuthUserContext;
import com.dlc.shop.security.platform.util.SecurityUtils;
import com.dlc.shop.service.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;


/**
 * 商品列表、商品发布controller
 *
 * @author lgh
 */
@RestController
@RequestMapping("/prod/prod")
@AllArgsConstructor
@Tag(name = "商品")
@Slf4j
public class ProductController {

    private final SkuService skuService;
    private final BasketService basketService;
    private final ProductService productService;
    private final ApplicationEventPublisher eventPublisher;
    private final ApplicationContext applicationContext;
    private final OfflineHandleEventService offlineHandleEventService;
    private final SupplierProdService supplierProdService;
    private final ProdParameterService prodParameterService;
    private final SeckillService seckillService;


    private final ShopDetailService shopDetailService;
    private final GiveawayProdService giveawayProdService;
    private final ComboProdService comboProdService;
    private final SegmentService segmentService;

    private WarehouseService warehouseService;
    private StationService stationService;
    private final ForeignProductService foreignProductService;

    @GetMapping("/seckills")
    @Operation(summary = "分页获取秒杀商品信息")
    @PreAuthorize("@pms.hasPermission('prod:prod:pageSeckill')")
    public ServerResponseEntity<IPage<Product>> seckills(ProductParam product, PageParam<Product> page){
        product.setLang(I18nMessage.getLang());
        IPage<Product> productPage = seckillService.pageSeckillNormalProd(page, product);
        return ServerResponseEntity.success(productPage);
    }

    /**
     * 处理下活动商品的价格
     *
     * @param product
     * @param products
     */
    private void processActivityProdPrice(ProductParam product, List<Product> products) {
        Map<Integer, List<Product>> prodMap = products.stream().collect(Collectors.groupingBy(Product::getProdType));
        if (prodMap.containsKey(ProdType.PROD_TYPE_SECKILL.value())) {
            applicationContext.publishEvent(new ProcessActivityProdPriceEvent(product, prodMap.get(ProdType.PROD_TYPE_SECKILL.value())));
        }

        if (prodMap.containsKey(ProdType.PROD_TYPE_GROUP.value())) {
            applicationContext.publishEvent(new ProcessActivityProdPriceEvent(product, prodMap.get(ProdType.PROD_TYPE_GROUP.value())));
        }
    }

    @GetMapping("/info/{prodId}")
    @PreAuthorize("@pms.hasPermission('prod:prod:info')")
    @Operation(summary = "获取商品信息" , description = "获取商品信息")
    @Parameter(name = "prodId", description = "商品id" )
    public ServerResponseEntity<Product> info(@PathVariable("prodId") Long prodId) {
        Product prod = productService.getProductById(prodId);
        List<Sku> skuList = skuService.listSkuAndSkuStock(prodId, prod.getMold());
        Integer totalStock = 0;
        Set<Long> skuIds = getIsParticipate(prodId);
        for (Sku sku : skuList) {
            sku.setIsParticipate(skuIds.contains(sku.getSkuId()) ? 1 : 0);
            totalStock += Objects.isNull(sku.getStocks()) ? 0: sku.getStocks();
        }
        prod.setTotalStocks(totalStock);
        prod.setSkuList(skuList);

        List<ProdParameter> prodParameters = prodParameterService.listParameterByProdId(prodId);
        prod.setProdParameterList(prodParameters);
        return ServerResponseEntity.success(prod);
    }

    @DeleteMapping("/{prodId}")
    @PreAuthorize("@pms.hasPermission('prod:prod:update')")
    @Operation(summary = "平台删除商品" , description = "平台删除商品")
    @Parameter(name = "prodId", description = "商品id" )
    public ServerResponseEntity<Void> delete(@PathVariable("prodId") Long prodId) {
        this.checkBeforeDeleteProduct(prodId);
        Product dbProduct = productService.getProductByProdId(prodId);
        List<Sku> dbSkus = skuService.listSkuByProdId(dbProduct.getProdId());
        List<Long> supplierIds = supplierProdService.listSupplierIdByProdId(prodId);
        List<Long> deleteSkuIds = dbSkus.stream().map(Sku::getSkuId).toList();
        // 删除商品
        productService.removeProductByProdId(prodId,deleteSkuIds);
        //清除供应商商品列表缓存
        if (CollectionUtils.isNotEmpty(supplierIds)) {
            for (Long supplierId : supplierIds) {
                supplierProdService.removeCacheBySupplierId(supplierId);
            }
        }
        // 商品状态改变时的发送事件，让活动下线
        applicationContext.publishEvent(new ProdChangeStatusEvent(dbProduct, ProdStatusEnums.DELETE.getValue()));
        //清除商品缓存
        productService.removeProdCacheByProdId(prodId);

        //清除sku缓存
        for (Sku sku : dbSkus) {
            skuService.removeSkuCacheBySkuId(sku.getSkuId(), sku.getProdId());
        }
        List<String> userIds = basketService.listUserIdByProdId(prodId);

        //清除购物车缓存
        basketService.removeCacheByUserIds(userIds);
        // 删除商品时，改变分销设置,团购订单处理。。。
        applicationContext.publishEvent(new ProdChangeEvent(dbProduct));
        eventPublisher.publishEvent(new EsProductUpdateEvent(prodId, null, EsOperationType.DELETE));

        //调用 国外删除
        foreignProductService.delete(prodId);
        return ServerResponseEntity.success();
    }

    @GetMapping("/listProdByIdsAndType")
    @Operation(summary = "获取商品信息列表" , description = "获取商品信息列表")
    @PreAuthorize("@pms.hasPermission('prod:prod:list')")
    public ServerResponseEntity<List<Product>> listProdByIdsAndType(ProductParam product) {
        List<Product> products = productService.listProdByIdsAndType(product);
        processActivityProdPrice(product, products);
        return ServerResponseEntity.success(products);
    }

    @PutMapping("/waterSoldNum")
    @Operation(summary = "更新注水销量" , description = "更新注水销量")
    @Parameter(name = "prodId", description = "商品id" )
    @PreAuthorize("@pms.hasPermission('prod:prod:update')")
    public ServerResponseEntity<Void> updateWaterSoldNum(Integer waterSoldNum, Long prodId) {
        if (waterSoldNum == null) {
            waterSoldNum = 0;
        }
        productService.updateWaterSaleNum(waterSoldNum, prodId);
        eventPublisher.publishEvent(new EsProductUpdateEvent(prodId, null, EsOperationType.UPDATE_SOLD_NUM));
        return ServerResponseEntity.success();
    }

    @PostMapping("/offline")
    @PreAuthorize("@pms.hasPermission('prod:prod:update')")
    @Operation(summary = "下线商品" , description = "下线商品")
    public ServerResponseEntity<Void> offline(@RequestBody OfflineHandleEvent offlineHandleEvent) {
        Product dbProduct = productService.getProductAndLang(offlineHandleEvent.getHandleId());
        if (dbProduct == null) {
            // 未找到刚商品的信息
            throw new YamiShopBindException("yami.product.not.exist");
        }
        if(Objects.equals(dbProduct.getStatus(), ProdStatusEnums.PLATFORM_OFFLINE.getValue())){
            // 该商品已被下架
            throw new YamiShopBindException("yami.platform.prod.offline.check");
        }
        Long sysUserId = SecurityUtils.getSysUser().getUserId();
        OfflineHandleEvent offline = productService.offline(offlineHandleEvent.getHandleId(), offlineHandleEvent.getOfflineReason(), sysUserId);

        // 商品状态改变时的发送事件，让活动下线
        applicationContext.publishEvent(new ProdChangeStatusEvent(dbProduct, ProdStatusEnums.PLATFORM_OFFLINE.getValue()));
        List<String> userIds = basketService.listUserIdByProdId(dbProduct.getProdId());
        //清除购物车缓存
        basketService.removeCacheByUserIds(userIds);
        // 移除缓存
        productService.removeProdCacheByProdId(dbProduct.getProdId());
        eventPublisher.publishEvent(new EsProductUpdateEvent(dbProduct.getProdId(), null, EsOperationType.UPDATE));
        //发送商品下架提醒给商家
        NotifyTemplateParam shopParam = new NotifyTemplateParam();
        shopParam.setShopId(dbProduct.getShopId());
        shopParam.setProdId(offlineHandleEvent.getHandleId());
        shopParam.setProdName(dbProduct.getProdName());
        shopParam.setSendType(SendType.PRODUCT_OFFLINE.getValue());
        applicationContext.publishEvent(new SendMessageEvent(shopParam));

        foreignProductService.offline(offline);
        return ServerResponseEntity.success();
    }

    @GetMapping("/getOfflineHandleEventByProdId/{prodId}")
    @Operation(summary = "获取最新下线商品的事件" , description = "获取最新下线商品的事件")
    @Parameter(name = "prodId", description = "商品id" )
    @PreAuthorize("@pms.hasPermission('prod:prod:offlineInfo')")
    public ServerResponseEntity<OfflineHandleEvent> getOfflineHandleEventByProdId(@PathVariable Long prodId) {
        OfflineHandleEvent offlineHandleEvent = offlineHandleEventService.getProcessingEventByHandleTypeAndHandleId(OfflineHandleEventType.PROD.getValue(), prodId);
        return ServerResponseEntity.success(offlineHandleEvent);
    }

    @PostMapping("/prodOfflineAudit")
    @Operation(summary = "审核违规下架的商品" , description = "审核违规下架的商品")
    @PreAuthorize("@pms.hasPermission('prod:prod:update')")
    public ServerResponseEntity<Void> prodOfflineAudit(@RequestBody OfflineHandleEventAuditParam offlineHandleEventAuditParam) {
        Long userId = SecurityUtils.getSysUser().getUserId();
        productService.prodAudit(offlineHandleEventAuditParam, userId);
        // 移除缓存
        productService.removeProdCacheByProdId(offlineHandleEventAuditParam.getHandleId());
        eventPublisher.publishEvent(new EsProductUpdateEvent(offlineHandleEventAuditParam.getHandleId(), null, EsOperationType.UPDATE));

        offlineHandleEventAuditParam.setHandleId(userId);
        foreignProductService.prodOfflineAudit(offlineHandleEventAuditParam);
        return ServerResponseEntity.success();
    }



    @PutMapping("/toTop/{id}")
    @Operation(summary = "置顶商品" , description = "置顶商品")
    @Parameter(name = "id", description = "商品id" )
    @PreAuthorize("@pms.hasPermission('prod:prod:update')")
    public ServerResponseEntity<Void> removeById(@PathVariable Long id) {
        Product product = productService.getProductByProdId(id);
        if (!Objects.equals(product.getStatus(), ProdStatusEnums.NORMAL.getValue())) {
            // 只能置顶已上架的商品
            throw new YamiShopBindException("yami.prod.set.top.check");
        }
        product.setIsTop(Objects.equals(product.getIsTop(), 0) ? 1 : 0);
        productService.updateById(product);
        // 移除缓存
        productService.removeProdCacheByProdId(id);
        eventPublisher.publishEvent(new EsProductUpdateEvent(product.getProdId(), null, EsOperationType.UPDATE));
        return ServerResponseEntity.success();
    }

    private void checkBeforeDeleteProduct(Long prodId) {
        GetComboProdCountEvent getComboProdCountEvent = new GetComboProdCountEvent();
        getComboProdCountEvent.setProdId(prodId);
        applicationContext.publishEvent(getComboProdCountEvent);
        if (getComboProdCountEvent.getCount() > 0) {
            //参加以下活动的商品不能被删除：优惠套餐
            throw new YamiShopBindException("yami.combo.prod.not.delete");
        }
        GetGiveawayProdCountEvent getGiveawayProdCountEvent = new GetGiveawayProdCountEvent();
        getGiveawayProdCountEvent.setProdId(prodId);
        applicationContext.publishEvent(getGiveawayProdCountEvent);
        if (getGiveawayProdCountEvent.getCount() > 0) {
            //参加以下活动的商品不能被删除：赠品
            throw new YamiShopBindException("yami.giveaway.prod.not.delete");
        }
    }

    //审核商品
    @PostMapping("/auditProd")
    @Operation(summary = "审核待审核的商品" , description = "商品审核开关打开后，新发布的或要上架的商品处于的待审核状态")
    @PreAuthorize("@pms.hasPermission('prod:prod:update')")
    public ServerResponseEntity<Void> auditProd(@RequestBody OfflineHandleEvent offlineHandleEvent) {
        Long prodId = offlineHandleEvent.getHandleId();
        Product dbProduct = productService.getProductByProdId(prodId);
        if (Objects.isNull(dbProduct)) {
            // 未找到刚商品的信息
            throw new YamiShopBindException("yami.product.not.exist");
        }
        if (!Objects.equals(dbProduct.getStatus(), ProdStatusEnums.AUDIT.getValue())) {
            // 商品状态已改变，请刷新页面
            throw new YamiShopBindException("yami.prod.status.change");
        }
        offlineHandleEvent.setHandlerId(SecurityUtils.getSysUser().getUserId());
        //updatePrice(productParam);
        productService.handleAuditProd(dbProduct, offlineHandleEvent);
        // 移除缓存
        productService.removeProdCacheByProdId(dbProduct.getProdId());
        eventPublisher.publishEvent(new EsProductUpdateEvent(dbProduct.getProdId(), null, EsOperationType.UPDATE));
        if (Objects.equals(offlineHandleEvent.getStatus(), OfflineHandleEventStatus.AGREE_BY_PLATFORM.getValue())) {
            // 审核通过
            offlineHandleEvent.setShopId(dbProduct.getShopId());
            foreignProductService.auditProd(offlineHandleEvent);
        }
        return ServerResponseEntity.success();
    }

    @PutMapping("/updateProd")
    @Operation(summary = "待审核的商品修改" , description = "修改完成商品后进行审核")
    @PreAuthorize("@pms.hasPermission('prod:prod:update')")
    public ServerResponseEntity<Long> updatePrice(@Valid @RequestBody ProductParam productParam) {
        checkParam(productParam);
        //YamiShopUser shopUser = SecurityUtils.getShopUser();
        Product dbProduct = productService.getProductById(productParam.getProdId());
        //if (!Objects.equals(productParam.getPreSellStatus(), dbProduct.getPreSellStatus()) && Objects.equals(productParam.getPreSellStatus(), StatusEnum.ENABLE.value())) {
        //    // 预售商品不能
        //    long count = comboProdService.count(new LambdaQueryWrapper<ComboProd>()
        //            .eq(ComboProd::getProdId, productParam.getProdId())
        //            .gt(ComboProd::getStatus, StatusEnum.DISABLE.value())
        //    );
        //    if (count > 0) {
        //        throw new YamiShopBindException("yami.prod.not.pre");
        //    }
        //}
       // productParam.setEmployeeId(shopUser.getEmployeeId());
       // productParam.setEmployeeMobile(shopEmployeeService.getShopEmployeeById(productParam.getEmployeeId()).getMobile());
        if (Objects.equals(dbProduct.getStatus(), ProdStatusEnums.DELETE.getValue())) {
            // 产品已被删除
            throw new YamiShopBindException("yami.product.service.delete");
        }
        if (Objects.equals(dbProduct.getStatus(), ProdStatusEnums.PLATFORM_OFFLINE.getValue())) {
            productParam.setStatus( ProdStatusEnums.PLATFORM_OFFLINE.getValue());
        }
        //if (!Objects.equals(dbProduct.getShopId(), SecurityUtils.getShopUser().getShopId())) {
        //    // 查找不到该商品信息
        //    throw new YamiShopBindException("yami.product.not.exist");
        //}

        if (!Objects.equals(dbProduct.getProdType(), productParam.getProdType())) {
            // 商品类型改变，请刷新页面后重试
            throw new YamiShopBindException("yami.prod.type.check");
        }

        if (!Objects.equals(dbProduct.getMold(), productParam.getMold())) {
            // 商品创建后不能修改商品类型
            throw new YamiShopBindException("yami.order.prod.type.check");
        }
        //Long shopId = shopUser.getShopId();
        Long shopId = productParam.getShopId();
        ShopDetail shopDetail = shopDetailService.getShopDetailByShopId(shopId);
        if (Objects.equals(shopDetail.getShopStatus(), ShopStatus.OFFLINE.value())) {
            // 店铺处于违规下线中，不能修改商品，请联系管理员后重试
            throw new YamiShopBindException("yami.product.shop.offline");
        }
        //this.checkCategoryAndBrand(shopId, productParam.getCategoryId(), productParam.getShopCategoryId(), productParam.getBrandId());
        List<String> userIds = basketService.listUserIdByProdId(productParam.getProdId());
        List<Sku> dbSkus = skuService.listSkuAndSkuStock(dbProduct.getProdId(), null);

        dbProduct.setSkuList(dbSkus);
        productParam.setProdType(productParam.getProdType());
        productService.updateProduct(productParam, dbProduct);
        //checkGiveawayProd(productParam.getProdId());
        //清除购物车缓存
        basketService.removeCacheByUserIds(userIds);
        productService.removeProdCacheByProdId(productParam.getProdId());
        prodParameterService.removeCacheByProdId(productParam.getProdId());
        for (Sku sku : dbSkus) {
            skuService.removeSkuCacheBySkuId(sku.getSkuId(), sku.getProdId());
        }
        applicationContext.publishEvent(new ProdChangeStatusEvent(dbProduct, productParam.getStatus()));
        applicationContext.publishEvent(new ComboEvent(dbProduct, productParam.getStatus()));
        eventPublisher.publishEvent(new EsProductUpdateEvent(productParam.getProdId(), null, EsOperationType.UPDATE));
        //平台修改数据 同步数据
        foreignProductService.update(productParam);
        return ServerResponseEntity.success(Objects.equals(productParam.getStatus(), ProdStatusEnums.NORMAL.getValue()) ? productParam.getProdId() : null);
    }

    private void checkParam(ProductParam productParam) {
        Long prodId = productParam.getProdId();
        Product.DeliveryModeVO deliveryMode = productParam.getDeliveryModeVo();
        boolean hasDeliverMode = deliveryMode != null
                && (deliveryMode.getHasShopDelivery() || deliveryMode.getHasUserPickUp() || deliveryMode.getHasCityDelivery());
        if (!hasDeliverMode) {
            // 请选择配送方式
            throw new YamiShopBindException("yami.product.dvy.type");
        }
        if (Objects.equals(productParam.getMold(), 1)) {
            // 虚拟商品的配送方式
            Product.DeliveryModeVO mode = new Product.DeliveryModeVO();
            mode.setHasShopDelivery(true);
            mode.setHasUserPickUp(false);
            mode.setHasCityDelivery(false);
            productParam.setDeliveryModeVo(mode);
        }
        //校验参与活动的sku不能修改价格
        Set<Long> skuIds = getIsParticipate(prodId);
        List<Sku> skus = new ArrayList<>();
        if (CollUtil.isNotEmpty(skuIds)) {
            skus = skuService.listSkuByProdId(prodId);
        }
        Map<Long, Double> skuMap = skus.stream().collect(Collectors.toMap(Sku::getSkuId, Sku::getPrice));
        List<SkuAdminDTO> skuList = productParam.getSkuList();
        Long shopId = productParam.getShopId();
        //商品编码
        List<Product> products = productService.list(new LambdaQueryWrapper<Product>().eq(Product::getShopId, shopId)
                .ne(Product::getStatus, -1));
        List<Long> prodIds = products.stream().map(Product::getProdId).collect(Collectors.toList());
        List<String> partyCodes = skuService.listSkuByProdIds(prodIds, prodId);
        // 校验sku
        checkSku(skuList, partyCodes);

    }
    @NotNull
    private Set<Long> getIsParticipate(Long prodId) {
        List<GiveawayProd> giveawayProds = giveawayProdService.list(new LambdaQueryWrapper<GiveawayProd>()
                .eq(GiveawayProd::getProdId, prodId)
                .eq(GiveawayProd::getStatus, 1));
        Set<Long> skuIds = giveawayProds.stream().map(GiveawayProd::getSkuId).collect(Collectors.toSet());
        List<ComboProdVO> comboProdList = comboProdService.listComboProdByProdId(prodId);
        for (ComboProdVO comboProd : comboProdList) {
            skuIds.addAll(comboProd.getSkuList().stream().map(ComboProdSkuVO::getSkuId).collect(Collectors.toSet()));
        }
        return skuIds;
    }
    private void checkSku(List<SkuAdminDTO> skuList, List<String> partyCodes) {
        boolean isAllUnUse = true;
        for (SkuAdminDTO sku : skuList) {
            //雪花算法生成商品编码
            if (StrUtil.isBlank(sku.getPartyCode())) {
                String partyCode = StringUtils.join("RM", String.valueOf(segmentService.getSegmentId(SegmentIdKey.PRODUCT)));
                sku.setPartyCode(partyCode);
            }
            if (CollectionUtils.isNotEmpty(partyCodes) && partyCodes.contains(sku.getPartyCode())) {
                String message = I18nMessage.getMessage("yami.sku.party.code");
                String isExit = I18nMessage.getMessage("yami.is.exist");
                //商品编码已存在
                throw new YamiShopBindException(message + sku.getPartyCode() + isExit);
            }
            // sku价格最低只能为0.01
            if (Constant.MIN_PRODUCT_AMOUNT > sku.getPrice()) {
                sku.setPrice(Constant.MIN_PRODUCT_AMOUNT);
            }
            if (1 == sku.getStatus()) {
                isAllUnUse = false;
            }
            if (Objects.isNull(sku.getStockWarning())) {
                sku.setStockWarning(0);
            }
            if(sku.getStockWarning()>Constant.STOCK_WARNING_MAX){
                //超过库存预警最大值
                throw new YamiShopBindException("yami.sku.stockWarning.limit");
            }
        }
        if (isAllUnUse) {
            // 至少要启用一种商品规格
            throw new YamiShopBindException("yami.product.enable.sku");
        }
    }

    @GetMapping("/stockPoint")
    @Operation(summary = "获取店铺库存点数据")
    public ServerResponseEntity<StockPointVO> pointList(Long shopId) {
        StockPointVO stockPointVO = warehouseService.getWarehousePoint(shopId, SysTypeEnum.MULTISHOP.value());
        Integer stationSize = (int) stationService.count(new LambdaQueryWrapper<>(Station.class).eq(Station::getShopId, shopId).eq(Station::getStockMode, StockModeEnum.SINGLE_STOCK.value()));
        stockPointVO.setStationSize(stationSize);
        return ServerResponseEntity.success(stockPointVO);
    }

    @PostMapping("/translate")
    @Operation(summary = "翻译接口", description = "翻译接口")
    public ServerResponseEntity<List<TranslateResponDto>> translate(@RequestBody TranslateRequestDto title) {
        List<TranslateResponDto> list = new ArrayList<>();

        for (String lang : title.getLang()) {
            String sourceTitle = "";
            try {
                //URLEncoder.encode(title.getTitle(),"UTF-8")
                sourceTitle = TranslateUtil.text(
                        "text", lang,"zh", title.getTitle(), "general");
            } catch (Exception e) {
                log.info(title.getTitle() + "语言：" + lang + "----->翻译失败！");
                sourceTitle = "翻译失败，请重试！";
            }
            TranslateResponDto translateResponDto = new TranslateResponDto();
            translateResponDto.setTitle(title.getTitle());
            translateResponDto.setLang(lang);
            translateResponDto.setSourceTitle(sourceTitle);
            list.add(translateResponDto);
        }

        return ServerResponseEntity.success(list);

    }


    @GetMapping("/zeroPage")
    @Operation(summary = "已参与零元购列表")
    public ServerResponseEntity<IPage<Product>> getZeroPage(PageParam<Product> page) {
        return ServerResponseEntity.success(productService.getZeroPage(page));
    }

    @GetMapping("/noZeroPage")
    @Operation(summary = "未参与零元购列表")
    public ServerResponseEntity<IPage<Product>> noZeroPage(PageParam<Product> page) {
        return ServerResponseEntity.success(productService.noZeroPage(page));
    }

    @PostMapping("/addZero")
    @Operation(summary = "参与零元购")
    public ServerResponseEntity<Void> addZero(@RequestBody Long[] ids) {
        productService.addZero(ids);
        return ServerResponseEntity.success();
    }

    @DeleteMapping("/deleteZero")
    @Operation(summary = "不参与零元购")
    public ServerResponseEntity<Void> deleteZero(@RequestBody Long[] ids) {
        productService.deleteZero(ids);
        return ServerResponseEntity.success();
    }
}
